<!-- 维修执行页面 -->
<template>
  <div class="pending-repair">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :search.sync="search"
        :data="data"
        :before-open="beforeOpen"
        v-model="form"
        :page.sync="page"
        ref="crud"
        :permission="permissionList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @row-dblclick="rowDblclick"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click="handleRma" :disabled="selectionList.length != 1">RMA处理</el-button>
          <el-button icon="el-icon-delete" type="danger" size="small" :disabled="selectionList.length === 0" @click="handleDelete()">删除</el-button>
        </template>
        <!--        <template slot="menuRight">-->
        <!--          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
        <!--        </template>-->
        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" size="small" @click="viewRepair(row)">维修详情</el-button>
          <el-button type="text" size="small" @click="viewHandle(row)">处理详情</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog class="dialog" append-to-body :close-on-click-modal="false" title="维修执行" v-if="repairDialog" :visible.sync="repairDialog" width="50%" top="5vh">
      <div class="sail-header-dialog-content">
        <avue-form ref="badConfirmProperties" v-model="badCodeModel" :option="badCodeOption"> </avue-form>
      </div>
      <div class="mark-btn" v-if="!badCodeOption.detail">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleRepair">提交</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-close" @click="handleBack">返回</el-button>
      </div>
    </el-dialog>
    <el-dialog class="dialog" append-to-body :close-on-click-modal="false" v-if="viewDialog" title="维修详情" :visible.sync="viewDialog" width="50%" top="20vh">
      <div class="sail-header-dialog-content">
        <div class="box-card-view">
          <div style="width: 50%">
            <ul style="display: flex; flex-direction: row">
              <li class="box-item-view">
                返厂数量：<span style="font-size: inherit; background: #81d3f8">{{ badCodeModel.rmaQuantity || 0 }}</span>
              </li>
              <li class="box-item-view">
                已完成：<span style="font-size: inherit; background: #ffff00">{{ badCodeModel.completedQuantity || 0 }}</span>
              </li>
              <li class="box-item-view">
                报废数：<span style="font-size: inherit; background: #caf982">{{ badCodeModel.scrapQuantity || 0 }}</span>
              </li>
            </ul>
          </div>
        </div>
        <div v-for="(item, index) in viewOptionList" :key="index">
          <avue-form ref="viewProperties" v-model="viewData[index]" :option="item"> </avue-form>
        </div>
      </div>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </div>
</template>

<script>
import { getList, ramHandle, getDetail, getDetailList, remove } from '@/api/repair/rma-handle';

import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

import userTableConfig from '@/components/user-table-config';

export default {
  name: 'rma-handle',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  data() {
    return {
      pageCode: 'rma-repair',
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      repairDialog: false,
      viewDialog: false,
      query: {},
      search: {},
      viewModel: {},
      badCodeModel: {},
      statisticsObj: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      loading: false,
      viewData: [],
      selectionList: [],
      data: [],
      viewOptionList: [],
      option: {
        header: true,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuPosition: 'right',
        border: true,
        index: false,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        searchLabelWidth: 120,
        labelWidth: 120,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchBtn: true,
        emptyBtn: true,
        viewBtn: false,
        // menuWidth: 100,
        columnBtn: false,
        column: [
          {
            label: 'RMA单号',
            prop: 'rmaNo',
            search: true,
            searchSpan: 6,
            searchOrder: 1,
            searchLabelWidth: 100,
            minWidth: 100,
            searchRules: [
              {
                required: false,
                message: '请输入RMA号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '销售出库单',
            prop: 'deliveryOrderNo'
          },
          {
            label: '客户名称',
            prop: 'partnerName',
            search: true,
            searchOrder: 2
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true,
            searchOrder: 3
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '订单数量',
            prop: 'orderQuantity'
          },
          {
            label: '出维修数',
            prop: 'repairedQuantity'
          },
          {
            label: '报废数',
            prop: 'scrapQuantity'
          },
          {
            label: '客户诉求',
            prop: 'clientConcern'
          },
          // {
          //   label: '是否有条码',
          //   prop: 'productSn'
          // },
          {
            label: '故障说明',
            prop: 'faultDescription'
          },
          {
            label: '状态',
            prop: 'productStatus',
            type: 'select',
            search: true,
            dicData: [
              {
                label: '待处理',
                value: 3
              },
              {
                label: '已处理',
                value: 4
              }
            ]
          }
        ]
      },
      badCodeOption: {
        submitBtn: false,
        emptyBtn: false,
        detail: false,
        group: [
          {
            label: '',
            arrow: false,
            prop: 'baseInfo',
            labelWidth: 110,
            column: [
              {
                label: '客户名称',
                prop: 'partnerName',
                span: 8,
                disabled: true
              },
              {
                label: '产品名称',
                prop: 'partName',
                span: 8,
                disabled: true
              },
              {
                label: '产品编码',
                prop: 'partNo',
                span: 8,
                disabled: true
              },
              {
                label: '产品型号',
                prop: 'partModel',
                span: 8,
                disabled: true
              },
              {
                label: '订单总数',
                prop: 'orderQuantity',
                span: 8,
                disabled: true
              },
              {
                label: '退回总数',
                prop: 'rmaQuantity',
                span: 8,
                disabled: true
              },
              {
                label: '退回率',
                prop: 'returnRate',
                span: 8,
                disabled: true
              },
              {
                label: '返修报废率',
                prop: 'returnRepairScrapRate',
                span: 8,
                disabled: true
              },
              //   {
              //     label: '返修报废率',
              //     prop: 'remark3332',
              //     span: 8,
              //     disabled: true
              //   },
              {
                label: '业务员',
                prop: 'salesman',
                span: 8,
                disabled: true
              },
              {
                label: '维修员',
                prop: 'repairerName',
                span: 8,
                disabled: true
              },
              {
                label: '申请退换日期',
                prop: 'createTime',
                span: 8,
                disabled: true
              },
              {
                label: '维修日期',
                prop: 'updateTime',
                span: 8,
                row: true,
                disabled: true
              },

              {
                label: '处理方式',
                prop: 'handleMode',
                type: 'select',
                span: 8,
                dicData: [
                  {
                    label: '返修发货',
                    value: '1'
                  },
                  {
                    label: '换新发货',
                    value: '2'
                  }
                ]
              },
              {
                label: '风险指数',
                prop: 'riskIndex',
                type: 'select',
                span: 8,
                dicData: [
                  {
                    label: '一级',
                    value: '一级'
                  },
                  {
                    label: '二级',
                    value: '二级'
                  },
                  {
                    label: '三级',
                    value: '三级'
                  }
                ]
              },
              {
                label: 'RMA费用统计',
                prop: 'rmaExpense',
                span: 8
              },
              {
                label: '质量原因',
                prop: 'returnFactor',
                type: 'select',
                span: 8,
                dicData: [
                  {
                    label: '质量原因',
                    value: '质量原因'
                  },
                  {
                    label: '其他原因',
                    value: '其他原因'
                  }
                ]
              }
            ]
          },
          {
            label: '问题描述',
            arrow: false,
            prop: 'question',
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '',
                prop: 'problemDescription',
                type: 'textarea',
                row: true,
                span: 24,
                minRows: 3,
                maxRows: 3
              },
              {
                label: '制程人',
                prop: 'processName',
                row: true,
                span: 8,
                type: 'search',
                appendClick: () => {
                  this.openPrincipalCommonModal();
                }
              }
            ]
          },
          {
            label: '原因分析',
            arrow: false,
            prop: 'reasonAnalysis',
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '',
                prop: 'reasonAnalysis',
                type: 'textarea',
                row: true,
                span: 24,
                minRows: 3,
                maxRows: 3
              }
            ]
          },
          {
            label: '流出原因',
            arrow: false,
            prop: 'outflowReason',
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '',
                prop: 'reasonOutflow',
                type: 'textarea',
                row: true,
                span: 24,
                minRows: 3,
                maxRows: 3
              }
            ]
          },
          {
            label: '短期对策',
            arrow: false,
            prop: 'shortTerm',
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '',
                prop: 'shortTermTeasure',
                type: 'textarea',
                row: true,
                span: 24,
                minRows: 3,
                maxRows: 3
              }
            ]
          },
          {
            label: '长期对策',
            arrow: false,
            prop: 'longTerm',
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '',
                prop: 'longTermMeasure',
                type: 'textarea',
                row: true,
                span: 24,
                minRows: 3,
                maxRows: 3
              }
            ]
          },
          {
            label: '效果确认',
            arrow: false,
            prop: 'effectConfirmation ',
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '',
                prop: 'effectConfirmation',
                type: 'textarea',
                row: true,
                span: 24,
                minRows: 3,
                maxRows: 3
              }
            ]
          }
        ]
      },
      viewBaseOption: {
        submitBtn: false,
        emptyBtn: false,
        detail: true,
        group: [
          {
            label: 'RMA基础信息',
            arrow: false,
            prop: 'baseInfo',
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: 'RMA号',
                prop: 'rmaNo',
                span: 8,
                disabled: true
              },
              {
                label: '销售出库单号',
                prop: 'deliveryOrderNo',
                span: 8,
                disabled: true
              },
              {
                label: '所属客户',
                prop: 'partnerName',
                span: 8,
                row: true,
                disabled: true
              },
              {
                label: '客户述求',
                prop: 'clientConcern',
                span: 8,
                disabled: true
              },
              {
                label: '退货原因',
                prop: 'reason',
                span: 8,
                disabled: true
              },
              {
                label: '业务员',
                prop: 'salesman',
                span: 8,
                disabled: true
              },
              {
                label: '不良现象',
                prop: 'failureName',
                type: 'select',
                disabled: true,
                span: 8,
                dicUrl: '/api/mes-product/mro/dict/list?dictType=FAILURE',
                props: {
                  label: 'name',
                  value: 'id'
                }
              },
              {
                label: '故障说明',
                prop: 'remark',
                disabled: true
              }
            ]
          }
        ]
      },
      viewRepairOption: {
        submitBtn: false,
        emptyBtn: false,
        detail: true,
        group: [
          {
            label: '维修信息',
            arrow: false,
            prop: 'repairInfo',
            icon: 'el-icon-vertical-bar',
            labelWidth: 120,
            column: [
              {
                label: '产品序列号',
                prop: 'productSn',
                span: 8,
                display: true,
                disabled: true
              },
              {
                label: '不良原因大类',
                prop: 'causeName',
                span: 8,
                disabled: true
              },
              {
                label: '不良原因小类',
                prop: 'subCauseName',
                span: 8,
                disabled: true
              },
              {
                label: '不良类型',
                prop: 'faultTypeName',
                type: 'select',
                dicUrl: '/api/mes-product/mro/dict/list?dictType=FAILURETYPE',
                props: {
                  label: 'name',
                  value: 'id'
                },
                span: 8,
                disabled: true
              },
              {
                label: '维修代码',
                prop: 'repairCode',
                disabled: true,
                span: 8
              },
              {
                label: '维修位号',
                prop: 'repairPositionNo',
                disabled: true,
                span: 8
              },
              {
                label: '维修用料',
                prop: 'repairMaterial',
                disabled: true,
                span: 8
              },
              {
                label: '维修结果',
                prop: 'status',
                disabled: true,
                span: 8
              },
              {
                label: '维修人',
                prop: 'repairerName',
                disabled: true,
                span: 8
              },

              {
                label: '维修说明',
                prop: 'repairDescription',
                type: 'textarea',
                display: true,
                row: true,
                disabled: true,
                minRows: 3,
                maxRows: 3
              },
              {
                label: '报废原因',
                prop: 'scrapCause',
                type: 'textarea',
                display: true,
                disabled: true,
                row: true,
                minRows: 3,
                maxRows: 3
              }
            ]
          }
        ]
      }
    };
  },
  watch: {},
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.viewData = this._cloneDeep([this.viewBaseOption]);
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleDelete() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    viewHandle(row) {
      this.badCodeOption.detail = true;
      this.repairDialog = true;
      this.getRmaHandleDetail(row);
    },
    getRmaHandleDetail(row) {
      getDetail({
        rmaProductId: row.rmaProductId
      }).then((res) => {
        let data = res.data.data || {};
        this.badCodeModel = {
          ...data,
          ...row
        };
      });
    },
    viewRepair(row) {
      getDetailList({
        rmaProductId: row.rmaProductId
      }).then((res) => {
        this.badCodeModel = row;
        let data = res.data.data || [];
        let baseData = [row];
        let arr = [];
        let viewData = this._cloneDeep([...baseData, ...data]);
        viewData.forEach((item, index) => {
          if (index === 0) {
            arr.push(this.viewBaseOption);
          } else {
            let group = this._cloneDeep(this.viewRepairOption.group);
            let repairInfo = this.findNode(group, 'repairInfo');
            let productSn = this.findObject(repairInfo.column, 'productSn');
            let repairDescription = this.findObject(repairInfo.column, 'repairDescription');
            let scrapCause = this.findObject(repairInfo.column, 'scrapCause');
            repairInfo.label = `维修信息${index}`;
            if (item.productSn) {
              productSn.display = true;
              repairDescription.display = false;
              scrapCause.display = true;
            } else {
              productSn.display = false;
              repairDescription.display = true;
              scrapCause.display = false;
            }
            let option = this._cloneDeep(this.viewRepairOption);
            option.group = group;
            arr.push(option);
          }
        });
        console.log(arr, viewData, 9999);
        this.viewOptionList = this._cloneDeep(arr);
        this.viewData = viewData;
      });
      this.viewDialog = true;
    },
    enterProductSequenceNumber() {},
    handleBack() {
      this.repairDialog = false;
    },
    handleRma() {
      this.badCodeOption.detail = false;
      this.badCodeModel = this.selectionList[0];
      this.getRmaHandleDetail(this.badCodeModel);
      this.repairDialog = true;
    },
    handleEmpty() {
      // this.$refs.badConfirmProperties.resetFields();
    },
    handleRepair() {
      let params = {
        rmaEntryId: this.badCodeModel.id,
        rmaProductId: this.badCodeModel.rmaProductId,
        handleMode: this.badCodeModel.handleMode,
        riskIndex: this.badCodeModel.riskIndex,
        rmaExpense: this.badCodeModel.rmaExpense,
        returnFactor: this.badCodeModel.returnFactor,
        problemDescription: this.badCodeModel.problemDescription,
        reasonAnalysis: this.badCodeModel.reasonAnalysis,
        reasonOutflow: this.badCodeModel.reasonOutflow,
        shortTermMeasure: this.badCodeModel.shortTermTeasure,
        longTermMeasure: this.badCodeModel.longTermMeasure,
        effectConfirmation: this.badCodeModel.effectConfirmation,
        processUser: this.badCodeModel.processUser,
        processName: this.badCodeModel.processName,
        remark: this.badCodeModel.remark
      };
      ramHandle(params).then((res) => {
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.onLoad();
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad();
    },
    searchChange(params, done) {
      this.query = params;
      this.onLoad(params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      params.productStatusStr = '3,4';
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.data = data.records || [];
        this.page.total = data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
    findNode(list = [], prop) {
      let node;
      list.forEach((ele) => {
        if (ele.prop === prop) node = ele;
      });
      return node;
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        // case 'repairCode':
        //   this.badCodeModel.repairCode = this._get(rowData, 'code', '');
        //   break;
        case 'principalModal':
          this.badCodeModel.processName = this._get(rowData, 'name', '');
          this.badCodeModel.processUser = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    openRepairCodeModel() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'repairCode';
      this.tableOption = {
        modalTitle: '选择维修代码信息（双击进行选择）',
        url: '/api/mes-product/mro/dict/list?dictType=ACTION',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },
    openPrincipalCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.mark-btn {
  display: flex;
  justify-content: flex-end;
}

.box-card {
  height: 80px;
  width: 174px;
  position: absolute;
  right: 6px;
  top: 54px;
  z-index: 100;
  li {
    font-size: 14px;
    height: 20px;
  }
}

.box-card-view {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  z-index: 100;
  li {
    font-size: 14px;
    height: 20px;
  }
}

li {
  list-style: none;
}

::v-deep .el-card__body {
  padding: 7px 0px 0px 0px;
}

.box-item {
  font-size: 15px !important;
  font-weight: bold !important;
  height: 20px !important;
}
.box-item-view {
  font-size: 15px !important;
  font-weight: bold !important;
  height: 20px !important;
  width: 140px !important;
}

.btn-repair {
  display: flex;
  margin: 15px;
  justify-content: flex-end;
}
</style>
